<script setup lang="ts">
import ToolView from "@/modules/tools/layout/tool-view.vue";
import { computed, ref } from "vue";
import { computedCatch } from "@/framework/vue/composable/computed-catch.ts";
import { AES, enc, Rabbit, RC4, TripleDES } from "crypto-js";

const algos = { AES, TripleDES, Rabbit, RC4 };
const options = Object.keys(algos).map(it => ({ value: it }));

const cypherInput = ref("今天吃什么");
const cypherAlgo = ref<keyof typeof algos>("AES");
const cypherSecret = ref("secret key");
const cypherOutput = computed(() => algos[cypherAlgo.value].encrypt(cypherInput.value, cypherSecret.value).toString());

const decryptInput = ref("U2FsdGVkX1/NIKQMXE1mr2LGMVotwkafAp5JFMDys3A=");
const decryptAlgo = ref<keyof typeof algos>("AES");
const decryptSecret = ref("secret key");
const [decryptOutput, decryptError] = computedCatch(
  () => algos[decryptAlgo.value].decrypt(decryptInput.value, decryptSecret.value).toString(enc.Utf8),
  {
    defaultValue: "",
    defaultErrorMessage: "Unable to decrypt your text",
  },
);
</script>

<template>
  <tool-view title="加密/解密文本" description="使用加密算法（如AES、TripleDES、Rabbit或RC4）加密和解密文本明文。">
    <div class="pv-20 full-view flex-center">
      <a-form class="w-80p" :label-col="{ span: 5 }">
        <a-divider orientation="left">
          <span class="color-text-secondary font-14">加密</span>
        </a-divider>
        <a-form-item label="加密内容">
          <a-textarea v-model:value="cypherInput" placeholder="请输入要加密的内容" :auto-size="{ minRows: 3, maxRows: 3 }" allow-clear />
        </a-form-item>
        <a-form-item label="密钥">
          <a-input allow-clear v-model:value="cypherSecret" />
        </a-form-item>
        <a-form-item label="算法">
          <a-select v-model:value="cypherAlgo" :options="options" />
        </a-form-item>
        <a-form-item label="加密结果">
          <a-textarea :value="cypherOutput" readonly :auto-size="{ minRows: 3, maxRows: 3 }" />
        </a-form-item>

        <a-divider orientation="left">
          <span class="color-text-secondary font-14">解密</span>
        </a-divider>
        <a-form-item label="解密内容">
          <a-textarea v-model:value="decryptInput" placeholder="请输入要解密的内容" :auto-size="{ minRows: 3, maxRows: 3 }" allow-clear />
        </a-form-item>
        <a-form-item label="密钥">
          <a-input allow-clear v-model:value="decryptSecret" />
        </a-form-item>
        <a-form-item label="算法">
          <a-select v-model:value="decryptAlgo" :options="options" />
        </a-form-item>
        <a-form-item label="解密结果">
          <a-textarea :value="decryptOutput" :status="decryptError && 'error'" readonly :auto-size="{ minRows: 3, maxRows: 3 }" />
          <template #extra>
            <span class="color-danger">{{ decryptError }}</span>
          </template>
        </a-form-item>
      </a-form>
    </div>
  </tool-view>
</template>

<style scoped lang="less"></style>
